package com.ruoyi.web.controller.client;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceHttpClientImpl;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.base.domain.ClientUser;
import com.ruoyi.base.service.ClientUserService;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.WxMiniAppConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.ResponseEntity;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import javax.annotation.Resource;
import java.util.Objects;


/**
 * @ClassName ClientPublicController
 * @Description TODO 客户端公共控制器
 * @Author Mr、Liu
 * @Date 2025/6/23 23:50
 * @Version 1.0
 */

@Api(tags = "客户端-公共控制器")
@RestController
@RequestMapping("/client/public")
public class ClientPublicController extends BaseController {


    @Value("${wx.pay.appId}")
    private String appid;
    @Value("${wx.pay.secret}")
    private String secret;


    @Autowired
    private ClientUserService clientUserService;

    @Resource
    private TokenService tokenService;

    @ApiOperation("登录")
    @GetMapping("/login/{code}")
    @Anonymous
    public ResponseEntity login(@PathVariable("code") String code) throws WxErrorException {

        if (StringUtils.isNull(code)) return new ResponseEntity().error("code为空");
        //测试校验
        if (code.equals("123456")) {
            String openid = code;
            ClientUser clientUser = clientUserService.getByOpenId(openid);
            if (Objects.isNull(clientUser)) {
                //新增用户信息
                clientUser = ClientUser.buildDefaultClientUser(appid, openid);
                clientUserService.save(clientUser);
            }
            LoginUser loginUser = clientUser.adapterLoginUser();
            String token = tokenService.createToken(loginUser);
            JSONObject ajax = new JSONObject();
            ajax.put(Constants.TOKEN, token);
            ajax.put("openId", openid);
            return new ResponseEntity().success(ajax);
        }

        WxMaService miniAppConfigById = this.getMiniAppConfigById();
        WxMaJscode2SessionResult wxMaJscode2SessionResult = miniAppConfigById.jsCode2SessionInfo(code);
        String openid = wxMaJscode2SessionResult.getOpenid();
        if (StringUtils.isBlank(openid)) return new ResponseEntity().error("登录异常");

        //根据openid查询用户信息
        ClientUser clientUser = clientUserService.getByOpenId(openid);
        if (Objects.isNull(clientUser)) {
            //新增用户信息
            clientUser = ClientUser.buildDefaultClientUser(appid, openid);
            clientUserService.save(clientUser);
        }
        LoginUser loginUser = clientUser.adapterLoginUser();
        String token = tokenService.createToken(loginUser);
        JSONObject ajax = new JSONObject();
        ajax.put(Constants.TOKEN, token);
        ajax.put("openId", openid);
        return new ResponseEntity().success(ajax);
    }

    /**
     * 获取小程序配置
     *
     * @return
     */
    @ApiOperation("获取小程序配置")
    private WxMaService getMiniAppConfigById() {
        WxMiniAppConfig wxMiniAppConfig = new WxMiniAppConfig();
        wxMiniAppConfig.setAppid(appid);
        wxMiniAppConfig.setSecret(secret);
        WxMaServiceHttpClientImpl wxMaServiceHttpClient = new WxMaServiceHttpClientImpl();
        //添加配置
        wxMaServiceHttpClient.addConfig(wxMiniAppConfig.getAppid(), wxMiniAppConfig);
        WxMaService wxMaService = wxMaServiceHttpClient.switchoverTo(wxMiniAppConfig.getAppid());
        return wxMaService;
    }

}
